﻿using ServiceStack;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace aier.wx.nosql.redis
{
    public class RedisClientManager
    {
        //去除ServiceStack限制
        static RedisClientManager()
        {
            var licenseKey = new LicenseKey()
            {
                Ref = "pedoc",
                Expiry = DateTime.Now.AddDays(365 * 5),
                Hash = string.Empty,
                Name = "pedoc",
                Type = LicenseType.Enterprise
            };
            var field = typeof(LicenseUtils).GetField("__activatedLicense",
            BindingFlags.Static | BindingFlags.NonPublic);
            var keyType = field.FieldType;
            var constructorInfos = keyType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
            var constructorInfo = constructorInfos[0];
            var key = constructorInfo.Invoke(new object[] { licenseKey });
            field.SetValue(null, key);
            var licenceAll = LicenseUtils.HasLicensedFeature(LicenseFeature.All);
        }

        private IRedisClientsManager redisManagerPool;

        public RedisClientManager(IRedisClientsManager redisManagerPool)
        {
            this.redisManagerPool = redisManagerPool;
        }


        public void UseRedisClient(Action<IRedisClient> action)
        {
            using (IRedisClient redisClient = redisManagerPool.GetClient())
            {
                action(redisClient);
            }
        }

        public TResult UseRedisClient<TResult>(Func<IRedisClient, TResult> action)
        {
            using (IRedisClient redisClient = redisManagerPool.GetClient())
            {
                return action(redisClient);
            }
        }
    }
}
